
//根据input[name]自动验证 input标签中属性使用 reg="name"优先使用标签内的正则 exist="user"提交表单前检测用户是否存在
var reglib = 
<?php 
	$root = realpath($_SERVER['CONTEXT_DOCUMENT_ROOT'].'/../');
	$regfile = "{$root}/app/Common/Common/reg.php";
	echo preg_replace('/\\\\/','\\',json_encode(require($regfile)));
?>;

$(function() {

	var tipArrowImageSrc = "/Public/plugins/EasyValidator/images/vtip_arrow.png";

	//自动填入正则表达式，

	$.fn.reg = function() {

		$(this).each(function() { //单个输入框填入正则表达式
			var self = $(this);
			
			
			if(self.is("select"))return;
			if(self.attr("readonly")!= undefined)return;
			
			if(self.attr("nocheck")!= undefined)return;
			var type=self.attr("type");
			var notVilidateType=['hidden','radio','checbox'];
			if(notVilidateType.indexOf(type) != -1 )return;//隐藏input不要验证
			
			

			var name = self.attr("name") + "";
			if(name == "undefined") return; //没有name的不要验证
			name = name.replace(/\[.*\]/g, "");

			var regAttr = self.attr("reg") + "";
			var r = name;

			if(regAttr == 'undefined') { //优先使用reg属性，在使用name属性
				r = name;
				if(reglib[r] == undefined) return; //没有reg属性就用名字，，没有名字的是不用验证的
			} else {
				r = regAttr;
				if(reglib[r] == undefined) return; //如果reg为 正则 返回true
			}
			

			self.attr("reg", String(reglib[r][0]));
			var placeholder = self.attr("placeholder") + "";
			if(placeholder == "undefined") self.attr("placeholder", String(reglib[r][1]));

		});
		return $(this);
	}

	$.fn.inputBeginValidate = function() {
		
		if($(this).parents('form').attr('nocheck') != undefined )return;
		//不要验证带有notcheck属性的表单

		$(this).reg();

		$(this).each(function() {
			var self = $(this);
			if(self.attr("readonly")!= undefined)return;
			var regAttr = $(this).attr("reg") + "";
			if(regAttr == "undefined") return;
			$(this).hover(
				function(e) {
					if($(this).attr('tip') != undefined) {
						var top = (e.pageY + yOffset);
						var left = (e.pageX + xOffset);
						var root = GetRootPath();
						$('body').append('<p id="vtip"><img id="vtipArrow" src="' + root + tipArrowImageSrc + '"/>' + $(this).attr('tip') + '</p>');
						$('p#vtip').css("top", top + "px").css("left", left + "px");
					}
				},
				function() {
					if($(this).attr('tip') != undefined) {
						$("p#vtip").remove();
					}
				}
			).mousemove(
				function(e) {
					if($(this).attr('tip') != undefined) {
						var top = (e.pageY + yOffset);
						var left = (e.pageX + xOffset);
						$("p#vtip").css("top", top + "px").css("left", left + "px");
					}
				}
			).blur(function() {
				//空值也要验证
				//if($(this).val() == '') return;
				if($(this).attr("reg") == undefined) {
					//ajax_validate($(this), this.tagName);
				} else {
					validate($(this), this.tagName);
				}
			});
			
			var form=$(this).parents("form");
			
			if(form.attr("v")=="true")return;
			form.attr("v","true");//阻止多次注册submit事件执行函数
			
			form.submit(function() {
				var isSubmit = true;
				$(this).find("[reg],[url]:not([reg])").each(function() {
					var self = $(this);
					if(self.attr("readonly")!= undefined)return;
					if($(this).attr('notcheck') != undefined )return;
					//不要验证带有notcheck属性的输入框
					
					
					if($(this).attr("reg") == undefined) {
						if(!ajax_validate($(this), this.tagName)) {
							isSubmit = false;
						}
					} else {
						if(!validate($(this), this.tagName)) {
							isSubmit = false;
						}
					}
				});
				//如果验证正确验证核对密码，同一表单两个密码框即是
				//if(isSubmit);

				window.__validate__ = isSubmit; //  validate 有冲突

				return isSubmit;

			});
			
			
		});

	}

	$("[name]").not("select").inputBeginValidate();
	//	$("[reg],[url]:not([reg]),[tip]").inputBeginValidate();

	function GetRootPath() {
		var rootPath = "";
		var path = location.pathname;
		var count = path.match(/\//g).length - 1;
		for(var i = 0; i < count; i++) {
			rootPath = rootPath + "../"
		}
		return rootPath;
	} //返回 ../../

	var xOffset = -20; // x distance from mouse
	var yOffset = 20; // y distance from mouse  

	//input tips

});

window.validate = function(obj, tagName) {

	var reg = new RegExp(obj.attr("reg"));
	var objValue = obj.val();
	if(!reg.test(objValue)) {
		if(tagName != "noChange") change_error_style(obj, tagName, "add");
		if(obj.attr("is_tip_null") == "yes") {
			obj.removeAttr("tip");
			obj.removeAttr("tip_bak");
		} else {
			obj.attr("tip", obj.attr("tip_bak"));
			obj.removeAttr("tip_bak");
		}
		return false;
	} else {
		if(obj.attr("url") == undefined) {
			obj.attr("tip", obj.attr("tip_bak"));
			obj.removeAttr("tip_bak");
			if(tagName != "noChange") change_error_style(obj, tagName, "remove");

			//如果正确，检查是否是核对项，是核对项核对
			var check = obj.attr("check") + "";
			if(check != "undefined") {
				var v = $("[name='" + check + "']").val();
				if(v == objValue) {
					change_error_style(obj, tagName, "remove");
					return true;
				} else {
					change_error_style(obj, tagName, "add");
					return false;
				}
			}

			//如果不是核对项直接返回true
			return true;
		} else {
			return ajax_validate(obj);
		}
	}
}

function ajax_validate(obj, tagName) {
	if(obj.attr("tip") == undefined) {
		obj.attr("is_tip_null", "yes");
	}
	var url_str = obj.attr("url");
	if(url_str.indexOf("?") != -1) {
		url_str = url_str + "&" + obj.attr("name") + "=" + obj.val();
	} else {
		url_str = url_str + "?" + obj.attr("name") + "=" + obj.val();
	}
	var feed_back = $.ajax({
		url: url_str,
		cache: false,
		async: false
	}).responseText;
	feed_back = feed_back.replace(/(^\s*)|(\s*$)/g, "");
	if(feed_back == 'success') {
		change_error_style(obj, tagName, "remove");
		if(obj.attr("is_tip_null") == "yes") {
			obj.removeAttr("tip");
			obj.removeAttr("tip_bak");
		} else {
			obj.attr("tip", obj.attr("tip_bak"));
			obj.removeAttr("tip_bak");
		}
		return true;
	} else {
		change_error_style(obj, tagName, "add");
		if(obj.attr("tip_bak") == undefined) {
			obj.attr("tip_bak", obj.attr("tip"));
			obj.attr("tip", feed_back);
		}
		return false;
	}
}
//更改错误样式
function change_error_style(obj, tagName, action_type) {
	if(tagName == "SELECT")return true;
	if(action_type == "add") {
		if(tagName == "SELECT") {
			obj.addClass("select_validation-failed");
		} else {
			obj.removeClass("input_right").removeClass("input_unknow").addClass("input_error");

		}
	} else {
		if(tagName == "SELECT") {
			obj.removeClass("select_validation-failed");
		} else {
			obj.removeClass("input_error").removeClass("input_unknow").addClass("input_right");
			//移除添加的错误信息提示
		}
	}
}

$(function() {
	window.isSubmit = false;

	$('[exist]').parents("form").submit(
		function() {

			if(window.isSubmit) return true; //拦截是否存在验证后返回true 提交表单
			if(!window.__validate__) return false; //如果前面验证不正确不用验证是否存在，反正就是不提交

			var form = $(this);
			var obj = $(this).find("[exist]").eq(0);
			obj.change(function() {
				window.__validate__ = false;
			});

			var module = obj.attr("exist");
			window.existSubmit = true;
			if(/^\-/.test(module)) {
				module = module.substr(1);
				window.existSubmit = false;
			}

			window.__validate__ = false; //等待exist验证
			$.post(form.attr("action"), {
				form: module + "Exist",
				name: obj.val()
			}, function(result) {
				window.__validate__ = true; //是否存在验证完成恢复一般验证结果
				if(!window.existSubmit) result = !result; //如果是不存在提交表单，把结果反过来执行
				if(result) {
					//移除添加的错误信息提示
					obj.removeClass("input_error").removeClass("input_unknow").addClass("input_right");
					window.isSubmit = true; //设为真提交表单	
					form.submit();
				} else {
					window.isSubmit = false;
					window.__validate__ = false; //设为false不提交表单
					obj.removeClass("input_right").removeClass("input_unknow").addClass("input_error");
				}
			});
			return false;
		}
	);
});